#ifndef H_BARO
#define H_BARO

#include "Arduino.h"

class Baro
{
private:
  static const float alpha=0.99;
  int ac1,ac2,ac3;
  unsigned int ac4,ac5,ac6;
  int b1,b2,mb,mc,md;

  long x1,x2,x3,b3,b5,b6;
  unsigned long b4,b7,last,lastTemp;

  byte oss;
public:
  long temp;
  float pressure;

  byte setup()
  {
    byte ret;

    oss=3;
    uint8_t buff[11*sizeof(int)];
#ifdef BMP085
    ret=fw.readBuf(BARO_ADDR, 0xAA, buff, 11*sizeof(int)); //read the gyro data from the ITG3200


    ac1=buff[0]<<8 | buff[1]; 
    ac2=buff[2]<<8 | buff[3];
    ac3=buff[4]<<8 | buff[5];
    ac4=buff[6]<<8 | buff[7];
    ac5=buff[8]<<8 | buff[9];
    ac6=buff[10]<<8 | buff[11];
    b1 =buff[12]<<8 | buff[13];
    b2 =buff[14]<<8 | buff[15];
    mb =buff[16]<<8 | buff[17];
    mc =buff[18]<<8 | buff[19];
    md =buff[20]<<8 | buff[21];


#endif

    return ret;
  }

  void update()
  {
    uint8_t buff[3];
    long UT,UP;
    static byte state;
    long p;
    static int count;

#ifdef BMP085
    if (state==0)
    {
      // start the read of the temp
      fw.write(BARO_ADDR, 0xF4, 0x2E);
      fw.stop();
      state=1;
      last=micros();
    }
    else if (state==1)
    {
      // wait & read temp
      if (micros()-last>4500) // 4.5 ms
      {
        fw.readBuf(BARO_ADDR, 0xF6, buff, 2);
        lastTemp=micros();
        UT=(buff[0]<<8 | buff[1]);

        x1=(((long)UT-(long)ac6)*(long)ac5)>>15;
        x2=((long)mc<<11)/(x1+md);
        b5=x1+x2;
        temp=(b5+8)>>4;

        state=2;
      }
    } 
    else if (state==2)
    {
      // send command to read pressure
      fw.write(BARO_ADDR,0xF4,0x34 | (oss<<6));
      fw.stop();
      last=micros();
      state=3;

    }
    else if (state==3)
    {
      if (micros()-last>25500) // 4.5-25.5ms depend on OSS
      {
        fw.readBuf(BARO_ADDR, 0xF6, buff, 3);
        UP=(unsigned long)buff[0]<<16 | (unsigned long)buff[1]<<8 | (unsigned long)buff[2];
        UP >>= (8-oss);

        b6 = b5 - 4000;
        // Calculate B3
        x1 = (b2 * (b6 * b6)>>12)>>11;
        x2 = (ac2 * b6)>>11;
        x3 = x1 + x2;
        b3 = (((((long)ac1)*4 + x3)<<oss) + 2)>>2;

        // Calculate B4
        x1 = (ac3 * b6)>>13;
        x2 = (b1 * ((b6 * b6)>>12))>>16;
        x3 = ((x1 + x2) + 2)>>2;
        b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;

        b7 = ((unsigned long)(UP - b3) * (50000>>oss));
        if (b7 < 0x80000000)
          p = (b7<<1)/b4;
        else
          p = (b7/b4)<<1;

        x1 = (p>>8) * (p>>8);
        x1 = (x1 * 3038)>>16;
        x2 = (-7357 * p)>>16;
        p += (x1 + x2 + 3791)>>4;  

        if (pressure==0.0) pressure=p/100.0;
        pressure=pressure*alpha+p/100.0*(1-alpha);
        state=0;

        if (micros()-lastTemp>=500e3) // in us second
          state=0; // read the temperature
        else
          state=2; // continue to read pressure
      }
    }
#endif
  }
}
baro;

#endif












































